package andriod.action.word;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javassist.bytecode.ByteArray;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.model.SEPX;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.hibernate.lob.SerializableBlob;
import org.w3c.dom.Document;

import com.jcrj.action.BaseAction;
import com.jcrj.dao.InfoManagerDao;
import com.jcrj.entity.ODocument;
import com.jcrj.entity.OFile;
import com.jcrj.entity.OInfoContent;
import com.jcrj.service.DocumentFlowService;
import com.jcrj.service.FileService;
import com.jcrj.service.InfoManagerService;

import andriod.service.ArdInfoService;

public class WordActoin extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 575313377763618019L;
	DocumentFlowService documentFlowService;
	InfoManagerService infoManagerService;
	ArdInfoService ardInfoService;
	private FileService fileService;

	private String fileArray;
	private String contentId;
	private String docId;
	private String docContent;

	public String getFileArray() {
		return fileArray;
	}

	public void setFileArray(String fileArray) {
		this.fileArray = fileArray;
	}

	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}

	// private InfoManagerDao infoManagerDao;
	// private InfoManagerService infoManagerService;

	// public InfoManagerDao getInfoManagerDao() {
	// return this.infoManagerDao;
	// }
	//
	// public void setInfoManagerDao(InfoManagerDao infoManagerDao) {
	// this.infoManagerDao = infoManagerDao;
	// }

	public String getContentId() {
		return contentId;
	}

	public void setContentId(String contentId) {
		this.contentId = contentId;
	}

	public String getDocId() {
		return docId;
	}

	public void setDocId(String docId) {
		this.docId = docId;
	}

	public String getDocContent() {
		return docContent;
	}

	public void setDocContent(String docContent) {
		this.docContent = docContent;
	}

	public void setDocumentFlowService(DocumentFlowService documentFlowService) {
		this.documentFlowService = documentFlowService;
	}

	public void setArdInfoService(ArdInfoService ardInfoService) {
		this.ardInfoService = ardInfoService;
	}

	public ArdInfoService getArdInfoService() {
		return this.ardInfoService;
	}

	public void setInfoManagerService(InfoManagerService infoManagerService) {
		this.infoManagerService = infoManagerService;
	}

	public InfoManagerService getInfoManagerService() {
		return this.infoManagerService;
	}

	public String saveWord() {
		try {
			File file = new File("F:/1401595499372.doc");
			FileInputStream in = new FileInputStream(file);
			byte[] content = new byte[(int) file.length()];
			int i = 0;
			int ind = 0;
			while ((i = in.read()) != -1) {
				content[ind++] = (byte) i;
			}

			this.ardInfoService.saveInfoContent(contentId, content);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public String saveDoc() {
		this.docContent = transToReadOnly(this.docContent);
		try {
			byte b[] = this.docContent.getBytes("UTF-8");
			ByteArrayInputStream bais = new ByteArrayInputStream(b);
			POIFSFileSystem poifs = new POIFSFileSystem();
			DirectoryEntry directory = poifs.getRoot();
			// DocumentEntry documentEntry =
			directory.createDocument("WordDocument", bais);
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			poifs.writeFilesystem(arrayOutputStream);// ----
			arrayOutputStream.flush();
			arrayOutputStream.close();
			byte[] content = arrayOutputStream.toByteArray();
			bais.close();
			this.ardInfoService.saveInfoContent(this.contentId, content);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String getWordViewWithDocId() {
		try {

			ODocument doc = this.documentFlowService.getDocumentById(Integer.parseInt(this.docId));
			if (doc == null) {
				return null;
			}
			String contentId = doc.getContentId();

			this.getWordViewByContentId(contentId);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public String getWordView() {
		// saveDoc(this.contentId);
		this.getWordViewByContentId(this.contentId);
		return null;
	}

	public String getWordViewByContentId(String contentId) {
		try {
			getResponse().setContentType("text/html;charset=utf-8");

			String htmlStr = this.getHtmlStr(contentId);
			
			htmlStr = htmlStr.replaceAll("font-size:10pt", "font-size:14pt");
			PrintWriter out = getResponse().getWriter();
			out.print(htmlStr);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return null;
	}

	public String getHtmlStr(String contentId) {

		String htmlStr = "";

		try {

			Blob blobContent = ardInfoService.getBlobContent(contentId);
			InputStream in = blobContent.getBinaryStream();

			htmlStr = convert2Html(in);

			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception ioe) {
				ioe.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return htmlStr;
	}

	public String convert2Html(InputStream fin) throws TransformerException, IOException, ParserConfigurationException, FileNotFoundException {
		
		// String rootPath = "/Users/Jared/Intellect/Workspace/docToHtml/";
		HWPFDocument wordDocument = new HWPFDocument(fin);
		
		final String cId = this.contentId;
		final String rootPath = getRequest().getRealPath("/");
		
		
		
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		 wordToHtmlConverter.setPicturesManager(new PicturesManager() {
		 public String savePicture(byte[] content, PictureType pictureType,
		 String suggestedName, float widthInches, float heightInches) {
		 // File file = new File("E:/test/" + suggestedName);
//		 String rootPath = "/Users/Jared/Intellect/Workspace/docToHtml/";
		 
		 File dir = new File(rootPath +"/wordImages/"+cId+"/");
		 if(!dir.exists()){
			 dir.mkdirs();
		 }
		 File file = new File(rootPath +"/wordImages/"+cId+"/"+ suggestedName);
		 try {
		 FileOutputStream out = new FileOutputStream(file);
		 out.write(content);
		 out.flush();
		 out.close();
		 // return "test/" + suggestedName;
		 return "/oa/"+"/wordImages/"+cId+"/"+ suggestedName;
		
		 } catch (IOException e) {
		 e.printStackTrace();
		 throw new RuntimeException();
		 }
		 }
		 });
		 PicturesTable picturesTable = wordDocument.getPicturesTable();
		 System.out.println(picturesTable.getAllPictures().size());
		
		
		
//		List<SEPX> sepxs = wordDocument.getSectionTable().getSections();
//		System.out.println(sepxs.size());
//		if (sepxs != null) {
//			for (int i = 0; i < sepxs.size(); i++) {
//				SEPX sepx = sepxs.get(i);
//				sepx.getSectionDescriptor();
//				System.out.println(sepx.getSectionDescriptor());
//				System.out.println(sepx.getSectionProperties());
//			}
//		}
		
		
		wordToHtmlConverter.processDocument(wordDocument);
		// // save pictures
		// List<Picture> pics =
		// wordDocument.getPicturesTable().getAllPictures();
		// if (pics != null) {
		// for (int i = 0; i < pics.size(); i++) {
		// Picture pic = (Picture) pics.get(i);
		// System.out.println();
		// try {
		// pic.writeImageContent(new FileOutputStream(rootPath +
		// pic.suggestFullFileName()));
		// } catch (FileNotFoundException e) {
		// e.printStackTrace();
		// }
		// }
		// }
		//
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();

		return new String(out.toByteArray(), "utf-8");
	}
	
	
	public String getWordEdit(){
		return getWordView();
	}
	
	public String getWordEdit_bak() {
		try {
			String htmlStr = this.getHtmlStr(this.contentId);
			htmlStr = this.transToEditable(htmlStr);

			InputStream responseIn = new ByteArrayInputStream(htmlStr.getBytes("utf-8"));
			getResponse().setContentType("text/html;charset=utf-8");
			OutputStream out = getResponse().getOutputStream();
			int i = 0;
			while ((i = responseIn.read()) != -1) {
				out.write(i);
			}
			try {
				if (responseIn != null) {
					responseIn.close();
				}
			} catch (Exception ioe) {
				ioe.printStackTrace();
			}

			try {
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (Exception ioe) {
				ioe.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public String transToEditable(String readOnlyStr) {
		String editableStr = "";

		Pattern p1 = Pattern.compile("<body.*?>");
		Matcher m1 = p1.matcher(readOnlyStr);
		if (m1.find()) {
			readOnlyStr = readOnlyStr.replaceFirst(m1.group(0), m1.group(0) + "<div contenteditable='true'>");
		}

		Pattern p2 = Pattern.compile("</body>");
		Matcher m2 = p2.matcher(readOnlyStr);

		if (m2.find()) {
			readOnlyStr = readOnlyStr.replaceFirst(m2.group(0), "</div>" + m2.group(0));
		}

		editableStr = readOnlyStr;
		return editableStr;
	}

	public String transToReadOnly(String editableStr) {
		String editableControlDivHead = "<\\s*div\\s+contenteditable\\s*=\\s*'true'\\s*>";
		String editableControlDivtail = "</\\s*div\\s*>";
		editableStr = editableStr.replaceAll(editableControlDivHead, "");
		editableStr = editableStr.replaceAll(editableControlDivtail, "</body>");
		return editableStr;
	}

	public String getInformationDetial() {
		try {
			String htmlStr = this.getHtmlStr(contentId);

			OutputStream out = getResponse().getOutputStream();
			PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
			// PrintWriter writer = new PrintWriter(out);
			JSONObject obj = new JSONObject();

			obj.put("content", htmlStr);
			// obj.put("fileList",
			// JSONArray.fromObject("[{\"createTime\":{\"date\":31,\"day\":6,\"hours\":14,\"minutes\":37,\"month\":4,\"nanos\":0,\"seconds\":13,\"time\":1401518233000,\"timezoneOffset\":-480,\"year\":114},\"fileSize\":91293,\"foreign\":0,\"id\":779540,\"name\":\"2-182.jpg\",\"note\":\"\",\"url\":\"admin/1401518233835.jpg\"},{\"createTime\":{\"date\":31,\"day\":6,\"hours\":14,\"minutes\":37,\"month\":4,\"nanos\":0,\"seconds\":26,\"time\":1401518246000,\"timezoneOffset\":-480,\"year\":114},\"fileSize\":21338,\"foreign\":0,\"id\":779541,\"name\":\"IMG0018A.jpg\",\"note\":\"\",\"url\":\"admin/1401518246898.jpg\"}]"));

			List<OFile> fileList = this.fileService.getFileList(fileArray);
			obj.put("fileList", fileList);
			// writer.print("\"fileList\":[{\"createTime\":{\"date\":31,\"day\":6,\"hours\":14,\"minutes\":37,\"month\":4,\"nanos\":0,\"seconds\":13,\"time\":1401518233000,\"timezoneOffset\":-480,\"year\":114},\"fileSize\":91293,\"foreign\":0,\"id\":779540,\"name\":\"2-182.jpg\",\"note\":\"\",\"url\":\"admin/1401518233835.jpg\"},{\"createTime\":{\"date\":31,\"day\":6,\"hours\":14,\"minutes\":37,\"month\":4,\"nanos\":0,\"seconds\":26,\"time\":1401518246000,\"timezoneOffset\":-480,\"year\":114},\"fileSize\":21338,\"foreign\":0,\"id\":779541,\"name\":\"IMG0018A.jpg\",\"note\":\"\",\"url\":\"admin/1401518246898.jpg\"}]");
			writer.print(obj.toString());

			// in.close();
			// out.flush();
			// out.close();
			writer.flush();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void writeFile(String content, String path) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}
}
